#!/bin/bash

DEFAULT_VARS_FILE=/opt/iiab/iiab/vars/default_vars.yml
LOCAL_VARS_FILE=/etc/iiab/local_vars.yml
IIAB_STATE_FILE=/etc/iiab/iiab_state.yml
#ROLE_NAME=""           # Don't initialize this
#ROLE_VAR=""            # No need to initialize this
#ANSIBLE_LOG_PATH=""    # Don't initialize this
INSTALL=false
ENABLED=false
REINSTALL=false
CWD=`pwd`
#ARGS="--extra-vars {"
ARGS="--extra-vars {\"skip_role_on_error\":False,"    # bash forces {...} to '{...}' for Ansible, SEE BOTTOM (IFS-like issue)
INVENTORY=ansible_hosts
PLAYBOOK=run-one-role.yml

if [ ! -f $PLAYBOOK ]; then
    echo "Exiting: IIAB Playbook not found."
    echo "Please run this in /opt/iiab/iiab (top level of git repo)."
    exit 1
fi

# https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash/14203146#14203146
while [[ $# -gt 0 ]]; do
    case $1 in    # if-else would do the job, but case statement allows for future changes...
        --reinstall)
            ARGS="$ARGS\"reinstall\":True,"    # Needs boolean not string so use JSON list
            REINSTALL=true
            ;;
        *)
            if [ ! -v ROLE_NAME ]; then    # Test whether var is not yet set
                ROLE_NAME="$1"
            elif [ ! -v ANSIBLE_LOG_PATH ]; then
                export ANSIBLE_LOG_PATH="$1"
            else
                echo "Too many argunments (ROLE_NAME and ANSIBLE_LOG_PATH already specified!)"
                exit 1
            fi
            ;;
    esac
    shift
done

if [ ! -v ROLE_NAME ]; then    # Test whether var is STILL not set!
    echo "Usage: ./runrole <name of role>"
    echo "Usage: ./runrole <name of role> --reinstall"
    echo
    echo "Optional 2nd parameter is full PATH/FILENAME for logging."
    echo "If omitted, <current directory>/iiab-debug.log is used."
    exit 1
fi

if [ ! -v ANSIBLE_LOG_PATH ]; then
    export ANSIBLE_LOG_PATH="$CWD/iiab-debug.log"    # Default log file location
fi


# 4 snippets to guide -> bootstrap -> accelerate role debugging on bare OS's:

mkdir -p /etc/iiab    # -p avoids errors, effectively like '|| true'
if [ ! -f /etc/iiab/local_vars.yml ]; then
    echo -e "\n\e[1mEXITING: /opt/iiab/iiab/runrole REQUIRES /etc/iiab/local_vars.yml\e[0m\n" >&2

    echo -e "(1) See http://FAQ.IIAB.IO -> What is local_vars.yml and how do I customize it?" >&2
    echo -e "(2) SMALL/MEDIUM/LARGE samples are included in /opt/iiab/iiab/vars" >&2
    echo -e "(3) NO TIME FOR DETAILS?  RUN INTERNET-IN-A-BOX'S FRIENDLY 1-LINE INSTALLER:\n" >&2

    echo -e '    https://download.iiab.io\n' >&2

    exit 1
fi

# In comparison, ./iiab-network and ./iiab-configure warn operators (IN RED)
# if run without the existence of /etc/iiab/iiab_state.yml
if [ ! -f  $IIAB_STATE_FILE ]; then    # touch $IIAB_STATE_FILE
    echo -e "\n\e[1mCreating... $IIAB_STATE_FILE\e[0m"
    cat > $IIAB_STATE_FILE << EOF
# DO *NOT* MANUALLY EDIT THIS, THANKS!
# IIAB does NOT currently support uninstalling apps/services.

EOF
fi

if ! command -v ansible > /dev/null; then
    echo -e "\n\e[1mPlease install Ansible, by running:\n\nsudo /opt/iiab/iiab/scripts/ansible\e[0m\n"
    exit 1
fi

mkdir -p /etc/ansible/facts.d
cp scripts/local_facts.fact /etc/ansible/facts.d/local_facts.fact


# Ansible role name & var name sometimes differ :/
if [ $ROLE_NAME == "calibre-web" ]; then
    ROLE_VAR=calibreweb
#elif [ $ROLE_NAME == "httpd" ]; then
#    ROLE_VAR=apache
elif [ $ROLE_NAME == "osm-vector-maps" ]; then    # TO BE REMOVED in 2026/2027
    ROLE_VAR=osm_vector_maps
else
    ROLE_VAR="$ROLE_NAME"
fi

echo
if $REINSTALL; then   # Add '_' so '--reinstall calibre' doesn't zap calibreweb
    if grep -q "^${ROLE_VAR}_" $IIAB_STATE_FILE; then
        echo -e "\e[1mThese line(s) in $IIAB_STATE_FILE are now being deleted:\e[0m\n"
        grep "^${ROLE_VAR}_" $IIAB_STATE_FILE; echo
        sed -i "/^${ROLE_VAR}_/d" $IIAB_STATE_FILE
    else
        echo -e "\e[1mERROR: $IIAB_STATE_FILE has no line(s) that begin with '${ROLE_VAR}_'\e[0m\n"
        echo -e "Try again without the '--reinstall' flag?\n"
        exit 1
    fi
else
    if grep -q "^${ROLE_VAR}_" $IIAB_STATE_FILE; then
        echo -e "\e[1mWARNING: $IIAB_STATE_FILE already has these line(s):\e[0m\n"
        grep "^${ROLE_VAR}_" $IIAB_STATE_FILE; echo
        echo -e "If you prefer to reinstall it, run: ./runrole --reinstall $1\n"

        grep -q "^${ROLE_VAR}_enabled:\s\+[Tt]rue\b" $DEFAULT_VARS_FILE && ENABLED=true
        grep -q "^${ROLE_VAR}_enabled:\s\+[Ff]alse\b" $LOCAL_VARS_FILE && ENABLED=false
        grep -q "^${ROLE_VAR}_enabled:\s\+[Tt]rue\b" $LOCAL_VARS_FILE && ENABLED=true
        if $ENABLED; then
            echo -n "Or just continue, to enforce var '${ROLE_VAR}_enabled: True' etc? [Y/n] "
        else
            echo -n "Or just continue, to enforce var '${ROLE_VAR}_enabled: False' etc? [Y/n] "
        fi
        read ans < /dev/tty
        echo
        [ "$ans" = "n" ] || [ "$ans" = "N" ] &&
            exit 1
    fi
fi

grep -q "^${ROLE_VAR}_install:\s\+[Tt]rue\b" $DEFAULT_VARS_FILE && INSTALL=true
grep -q "^${ROLE_VAR}_install:\s\+[Ff]alse\b" $LOCAL_VARS_FILE && INSTALL=false
grep -q "^${ROLE_VAR}_install:\s\+[Tt]rue\b" $LOCAL_VARS_FILE && INSTALL=true
if ! $INSTALL; then
    echo -e "\e[1m'${ROLE_VAR}_install: True' MUST BE SET!\e[0m\n"
    echo -e "Usually it's best to set variables in: $LOCAL_VARS_FILE\n"
    echo -n "Just for now, force '${ROLE_VAR}_install: True' directly to Ansible? [Y/n] "
    read ans < /dev/tty
    echo
    [ "$ans" = "n" ] || [ "$ans" = "N" ] &&
        exit 1
    ARGS="$ARGS\"${ROLE_VAR}_install\":True,"
fi


ARGS="$ARGS\"role_to_run\":\"$ROLE_NAME\"}"    # $ROLE_NAME works like \"$ROLE_NAME\" if str type validated
CMD="ansible-playbook -i $INVENTORY $PLAYBOOK --connection=local $ARGS"
echo -e "\e[1mbash will now run this, adding single quotes around the {...} curly braces:\e[0m\n\n$CMD\n"
ansible -m setup -i $INVENTORY localhost --connection=local | grep python
$CMD

# bash forces (NECESSARY) single quotes around {} at runtime (if $ARGS contains
# curly braces).  If you also add single quotes *within* $ARGS, Ansible will
# FAIL as you will end up with 2-not-1 single-quotes on each side of the {}.
# https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#json-string-format
#
# Change the top line of this file to 'bash -x' to see this happen live.  Or,
# if you prefer the single quotes in the $ARGS var itself, run it this way:
#
# echo $CMD > /tmp/runrole-ansible-cmd
# bash /tmp/runrole-ansible-cmd
